<template>
  <el-dialog :model-value="showAddParentDialog" :title="props.editInfo.id ? '编辑分类' : '新建分类'" width="500"
    :before-close="resetForm" :close-on-click-modal="false">
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入一级分类名称" />
      </el-form-item>
      <el-form-item label="副标题" prop="subhead">
        <el-input v-model="form.subhead" placeholder="请输入副标题" />
      </el-form-item>
      <el-form-item label="车型" prop="carIds">
        <el-select v-model="form.carIds" multiple placeholder="请选择" style="width: 100%" :disabled="isEdit">
          <el-option v-for="item in carList" :key="item.value" :label="`${item.label}(${item.tag})`"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="科目" prop="categoryIds">-->
      <!--        <el-select-->
      <!--          v-model="form.categoryIds"-->
      <!--          placeholder="请选择"-->
      <!--          style="width: 100%"-->
      <!--          :disabled="isEdit"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="item in categoryList"-->
      <!--            :key="item.value"-->
      <!--            :label="item.label"-->
      <!--            :value="item.value"-->
      <!--          >-->
      <!--          </el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <!--      <el-form-item label="映射页面" prop="pageUrlType">-->
      <!--        <el-select-->
      <!--          v-model="form.pageUrlType"-->
      <!--          placeholder="请选择"-->
      <!--          style="width: 100%"-->
      <!--          :disabled="isEdit"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="item in uniAppPageList"-->
      <!--            :key="item.value"-->
      <!--            :label="item.label"-->
      <!--            :value="item.value"-->
      <!--          >-->
      <!--          </el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <!--      <el-form-item-->
      <!--        label="类型"-->
      <!--        v-if="form.categoryIds === '1' || form.categoryIds === '4'"-->
      <!--        prop="remark"-->
      <!--      >-->
      <!--        <el-radio-group v-model="form.remark.type" :disabled="isEdit">-->
      <!--          <el-radio value="0">题库列表</el-radio>-->
      <!--          <el-radio value="1">视频课程</el-radio>-->
      <!--        </el-radio-group>-->
      <!--      </el-form-item>-->

      <!-- <el-form-item label="分类图片">
        <el-input v-model="form.img" style="display: none"></el-input>
        <div class="avatar-uploader" @click="showImageChooseDialog = true">
          <el-image v-if="categoryLogo" :src="categoryLogo" class="avatar" fit="contain"></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
              <Plus />
            </el-icon></i>
          <div v-if="categoryLogo" class="mask">替换</div>
          <el-icon v-if="categoryLogo" class="del-image" :size="20" @click.stop="handleDelImg">
            <CircleCloseFilled />
          </el-icon>
        </div>
      </el-form-item> -->
      <el-form-item label="用户权限" prop="isPay">
        <div>
          <el-radio-group v-model="form.isPay">
            <el-radio value="0">全部用户可看</el-radio>
            <el-radio value="1">仅限VIP会员可看</el-radio>
          </el-radio-group>
          <div style="color: #ccc;font-size: 12px;">选择“仅限VIP会员可看”时请先设置好会员权益</div>
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="submitForm(ruleFormRef)">确认</el-button>
        <el-button @click="resetForm">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
    :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
    :operationType="false"></image-selected-dialog>
</template>

<script setup lang="ts">
import { operationCategory } from '@/api/questionbanklabel'
import { Plus } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useUserStore } from '@/store/modules/user'

import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { getcarmodellist } from '@/api/questionbank'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'

const userStore = useUserStore()
let server = `${import.meta.env.VITE_API_URL}files`
let { accessToken } = userStore
const headers = { Authorization: 'Bearer ' + accessToken }
const categoryLogo = ref('')
// const typeOptions_two = [
//   {
//     value: '3',
//     label: '实拍讲解'
//   },
//   {
//     value: '4',
//     label: '考点视频'
//   }
// ]
const props = defineProps({
  showAddParentDialog: {
    type: Boolean
  },
  editInfo: {
    type: Object,
    default: () => {
      return {
        id: ''
      }
    }
  }
})

const isEdit = computed(() => {
  return props.editInfo.children && props.editInfo.children.length > 0
})

const ruleFormRef = ref<FormInstance>()

interface Form {
  name: string
  img: string
  parentId: number
  carIds: any
  categoryIds: string
  pageUrlType: string
  remark: { type: string }
  subhead: string
}

const form = reactive({
  name: '',
  img: '',
  categoryIds: '',
  pageUrlType: '',
  carIds: [],
  parentId: 0,
  remark: { type: '0' },
  status: 1,
  isPay: '0',
  subhead: ''
})

const rules = reactive<FormRules<Form>>({
  name: [{ required: true, message: '不能为空', trigger: 'blur' }],
  // img: [{ required: true, message: '不能为空', trigger: 'blur' }],
  carIds: [{ required: true, message: '不能为空', trigger: 'change', type: 'array' }],
  categoryIds: [{ required: true, message: '不能为空', trigger: 'change' }],
  remark: [{ required: true, message: '不能为空', trigger: 'blur' }],
  pageUrlType: [{ required: true, message: '不能为空', trigger: 'blur' }]
})

const editLoading = ref(false)

// const categoryList = [
//   {
//     label: '科目一',
//     value: '1'
//   },
//   {
//     label: '科目二',
//     value: '2'
//   },
//   {
//     label: '科目三',
//     value: '3'
//   },
//   {
//     label: '科目四',
//     value: '4'
//   }
// ]

// 临时指定小程序跳转页面
// const uniAppPageList = [
//   {
//     label: '精选500题',
//     value: '01'
//   },
//   {
//     label: '专项练习',
//     value: '02'
//   },
//   {
//     label: '图标技巧',
//     value: '03'
//   },
//   {
//     label: '考前密卷',
//     value: '04'
//   },
//   {
//     label: '分阶段练习',
//     value: '05'
//   }
// ]

interface carLists {
  label: string
  value: string
  tag: string
}
const carList = ref<Array<carLists>>([])

const emit = defineEmits(['closeDialog'])

const handleAvatarSuccess = (file: any) => {
  categoryLogo.value = file.data.url
  form.img = file.data.url
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (props.editInfo.id) {
        handleEdit()
      } else {
        handleAdd()
      }
    } else {
    }
  })
}

async function handleAdd() {
  try {
    editLoading.value = true
    form.img = categoryLogo.value
    let remark = JSON.stringify(form.remark)
    const res = await operationCategory.newAddCategory({
      ...form,
      carIds: form.carIds.join(','),
      remark,
      status: form.status
    })
    if (res.code === '00000') {
      emit('closeDialog', true, form.status)
      ElMessage.success('新增成功')
    }
  } catch (e) {
  } finally {
    editLoading.value = false
  }
}

async function handleEdit() {
  try {
    editLoading.value = true
    form.img = categoryLogo.value
    let remark = JSON.stringify(form.remark)
    const res = await operationCategory.eidtCategory(
      {
        name: form.name,
        img: form.img,
        carIds: form.carIds.join(','),
        remark,
        isPay: form.isPay,
        status: form.status
      },
      props.editInfo.id
    )
    if (res.code === '00000') {
      emit('closeDialog', true, form.status)
      ElMessage.success('编辑成功')
    }
  } catch (e) {
  } finally {
    editLoading.value = false
  }
}

//上传限制大小格式等
const beforeAvatarUpload = (file: any) => {
  const isLt2M = file.size / 10240 / 10240 < 2
  if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
    ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 20MB!!')
    return false
  }
}

const resetForm = () => {
  emit('closeDialog')
}

//车型下拉接口
const getcarmodellistinfo = async () => {
  let obj = {}
  const res = await getcarmodellist.getcarmodelId(obj)
  if (res.code == 0) {
    carList.value = res.data
  }
}

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const handleCloseImageDialog = (value: any) => {
  if (value.fileUrl) { categoryLogo.value = value.fileUrl }
  showImageChooseDialog.value = false
}
const handleDelImg = () => {
  categoryLogo.value = ''
}

onMounted(() => {
  if (props.editInfo.id) {
    form.name = props.editInfo.name
    form.img = props.editInfo.img
    form.isPay = String(props.editInfo.isPay)
    form.carIds = props.editInfo.carIds.split(',')
    categoryLogo.value = form.img
    const remarkObj = JSON.parse(props.editInfo.remark || '{}')
    form.remark.type = remarkObj.type || ''
  }

  form.pageUrlType = props.editInfo.pageUrlType
  form.categoryIds = props.editInfo.categoryIds
  form.parentId = props.editInfo.parentId

  getcarmodellistinfo()
})
</script>

<style scoped lang="scss">
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
